<?php

namespace app\admin\controller\basic;

use app\common\controller\Backend;
use think\Db;
use fast\Random;

/**
 * 学生列表
 */
class Students extends Backend
{

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;

        $ruleList = Db::name("classes")->select();
        // 如果查询结果为空，赋值为空数组
        $this->rulelist = is_array($ruleList) ? $ruleList : [];
        $ruledata = [0 => __('None')];
        foreach ($this->rulelist as $k => &$v) {
            $ruledata[$v['id']] = $v['name'];
        }
        $this->view->assign('ruledata', $ruledata);

        $ruleList = Db::name("parent")->select();
        $this->rulelist = is_array($ruleList) ? $ruleList : [];
        $ruledata = [];
        foreach ($this->rulelist as $k => &$v) {
            $ruledata[$v['id']] = $v['name'];
        }
        $this->view->assign('flagList', $ruledata);

        $ruleList = Db::name("school")->select();
        $this->rulelist = is_array($ruleList) ? $ruleList : [];
        $ruledata = [0 => __('None')];
        foreach ($this->rulelist as $k => &$v) {
            $ruledata[$v['id']] = $v['name'];
        }
         $this->view->assign('schoolList', $ruledata);
    }
 
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            // 获取请求参数
            $params = $this->request->param();

            // 查询数据（带分页）
            $list = $this->model
                ->with('studentClasses')
                ->with('school')
                ->where('type', 1)
                ->order($params['sort'] ?? 'id', $params['order'] ?? 'desc')
                ->paginate([
                    'list_rows' => $params['limit'] ?? 10,
                    'page'      => ($params['offset'] / $params['limit'] + 1) ?? 1
                ]);

            // 返回标准JSON格式
            $result = [
                "total" => $list->total(),
                "rows"  => $list->items()
            ];

            return json($result);
        }

        // 非AJAX请求返回视图
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post('row/a');
            // 验证必填字段
            if (empty($data['username']) || empty($data['email']) || empty($data['avatar']) || empty($data['mobile']) || empty($data['password'])) {
                $this->error('参数不能为空');
            }

            // 验证邮箱和手机号唯一性
            if ($this->model->where('email', $data['email'])->count() > 0) {
                $this->error('该邮箱已存在');
            }
            if ($this->model->where('mobile', $data['mobile'])->count() > 0) {
                $this->error('该手机号已存在');
            }

            // 提取关联数据
            $classId = $data['class_id'] ?? 0;
            $parentIds = $data['parent_id'] ?? [];
            unset($data['class_id'], $data['parent_id']);

            // 准备学生数据
            $data['type'] = 1;
            $data['salt'] = Random::alnum();
            $data['password'] = $this->getEncryptPassword($data['password'], $data['salt']);
            
            Db::startTrans();
            try {
                // 保存学生信息
                $result = $this->model->save($data);
                if (!$result) {
                    throw new \Exception('保存学生信息失败');
                }

                $studentId = $this->model->id;
                
                // 处理家长关联
                if (!empty($parentIds)) {
                    $parentRelations = array_map(function($parentId) use ($studentId) {
                        return [
                            'student_id' => $studentId,
                            'parent_id' => $parentId
                        ];
                    }, $parentIds);
                    
                    Db::name('student_parent_relation')->insertAll($parentRelations);
                }
                

                // 处理班级关联
                if ($classId) {
                    $classRelation = [
                        'student_id' => $studentId,
                        'classes_id' => $classId
                    ];
                    Db::name('student_classes_relation')->insert($classRelation);
                }
                
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('添加失败: '. $e->getMessage());
            }
        }
        
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {

            $data = $this->request->post('row/a');
            $row = $this->model->get($ids);

            $class_id = isset($data['class_id']) ? $data['class_id'] : [];
            unset($data['class_id']);

            $parent_ids = isset($data['parent_id']) ? $data['parent_id'] : [];
            unset($data['parent_id']);
            // 更新数据库
            $result = $row->save($data);

            if ($result === false) {
                // throw new \Exception('更新失败');
                $this->error('更新失败1');
            }

            if (!empty($ids)) {
                if(!empty($class_id)){
                    $classesModel = Db::name('student_classes_relation');
                    $classesModel->where('student_id', $ids)->delete();
                    $classesData = [
                        'student_id' => $ids,
                        'classes_id' => $class_id
                    ];
                    $classesModel->insert($classesData);
                }else{
                    $this->error('请选择班级');
                }
                // if (!empty($parent_ids)) {
                    $parentModel = Db::name('student_parent_relation');
                    $parentModel->where('student_id', $ids)->delete();
                    $insertData = [];
                    foreach ($parent_ids as $parentId) {
                        $insertData[] = [
                            'student_id' => $ids,
                            'parent_id' => $parentId
                        ];
                    }
                    $parentModel->insertAll($insertData);
                // }else{
                //     $this->error('请选择家长');
                // }
            }
    
        }
        $row = $this->model->get($ids);

        $relatedParent = Db::name('student_parent_relation')
            ->where('student_id', $ids)
            ->column('parent_id');

        // 查询当前学生关联的班级 ID
        $relatedClass = Db::name('student_classes_relation')
            ->where('student_id', $ids)
            ->value('classes_id');
        
        $schoolData = Db::name('school')
            ->where('id', $row['school_id'])
            ->value('id');

        $this->view->assign([
            'row' => $row,
            'relatedParent' => $relatedParent,
            'relatedClass' => $relatedClass,
            'schoolData' => $schoolData,
        ]);
        return parent::edit($ids);
    }

    /**
    * 删除
    * @param $ids
    */
    public function del($ids = null)
    {
        if ($ids) {
            $rows = $this->model->where('id', 'in', $ids)->delete();
            if ($rows) {
                Db::name('student_parent_relation')->where('student_id', 'in', $ids)->delete();
                Db::name('student_classes_relation')->where('student_id', 'in', $ids)->delete();
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
        $this->error('请选择要删除的记录');
    }
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }
}